<template>
  <a-modal :width="1300" v-model:visible="showEditDialog" title="编辑入库单" top="8vh" title-align="start" :on-before-ok="submitData" :ok-loading="submitLoading" :mask-closable="false" @cancel="closedDialog">
    <div class="header">
      <p class="title">基础信息</p>
    </div>
    <a-row class="detail-item">
      <a-col :span="12">
        <div class="flex">
          <p class="label">入库单号：</p>
          <div class="flex-c">
            <span class="highlight">{{ detailInfo.billNo }}</span>
            <CopyText style="margin-left: 5px" :val="detailInfo.billNo" />
          </div>
        </div>
      </a-col>
      <a-col :span="12">
        <div class="flex">
          <p class="label">收货仓：</p>
          <p class="val">{{ detailInfo.warehouseName }}（{{ detailInfo.warehouseCode }}）</p>
        </div>
      </a-col>
    </a-row>
    <a-row class="detail-item">
      <a-col :span="12">
        <div class="flex">
          <p class="label">申购方：</p>
          <p class="val">{{ detailInfo.companyName }}</p>
        </div>
      </a-col>
      <a-col :span="12">
        <div class="flex">
          <p class="label">采购方：</p>
          <p class="val">{{ detailInfo.purchaseOrgName }}</p>
        </div>
      </a-col>
    </a-row>
    <a-row class="detail-item">
      <a-col :span="12">
        <div class="flex">
          <span class="label" style="flex-shrink: 0">附件：</span>
          <ul style="margin-right: 10px" v-if="detailInfo.attachment">
            <li v-for="(url, i) in detailInfo.attachment.split(',')" style="margin-bottom: 4px" :key="i">
              <a-tag color="arcoblue" class="cursor" @click="downloadFile(url)">
                <span>{{ url }}</span>
                <icon-to-bottom />
              </a-tag>
            </li>
          </ul>
          <p v-else>--</p>
        </div>
      </a-col>
      <a-col :span="12">
        <div class="flex">
          <span class="label">备注：</span>
          <span style="flex: 1">{{ detailInfo.remark }}</span>
        </div>
      </a-col>
    </a-row>
    <a-row class="detail-item">
      <a-col :span="24">
        <div class="flex">
          <p class="label">收货地址：</p>
          <p class="val">{{ detailInfo.receivingAddress }}</p>
        </div>
      </a-col>
    </a-row>
    <div class="header" style="margin-top: 20px">
      <p class="title">明细信息</p>
    </div>
    <a-table class="table-two-line show-border-table" :bordered="{ cell: true }" :scroll="{ x: '100%', y: 'calc(84vh - 360px)' }" row-key="id" :columns="tableColumns" :data="detailInfo.billItems" size="mini" :pagination="false">
      <template #columns>
        <a-table-column v-for="(item, index) of tableColumns" :key="index" :fixed="item.fixed" :align="item.align" :width="item.width" :title="item.title" :data-index="item.dataIndex">
          <template #title v-if="item.tip">
            <a-popover>
              <template #content>
                <p v-for="(str, i) in item.tip.split('--')" :key="i" style="max-width: 500px">{{ str }}</p>
              </template>
              <p>
                <span>{{ item.title }}</span>
                <icon-question-circle />
              </p>
            </a-popover>
          </template>
          <template #cell="{ record, rowIndex }">
            <!-- 产品 -->
            <div v-if="item.dataIndex == 'sku'" class="flex-c">
              <ImgPopover :src="record.productImg">
                <template #con>
                  <a-image width="50" height="50" fit="contain" :src="record.productImg" />
                </template>
              </ImgPopover>
              <div style="margin-left: 5px; flex: 1">
                <ShowSpuDetailBySku :val="record.sku" :showLimit="true" :rows="1" />
                <TextLimit :val="getProductSpecs(record)" :rows="1" />
              </div>
            </div>
            <!-- 出仓 -->
            <div v-else-if="item.dataIndex == 'outWarehouse'" class="cell flex-c" style="width: 140px">
              <a-select v-model="record.warehouse" value-key="warehouseCode" style="width: 120px">
                <a-option v-for="(warehouseInfo, j) in useBaseData.warehouseList" :key="j" :value="warehouseInfo" :label="warehouseInfo.warehouseName" />
              </a-select>
              <icon-double-down v-if="showBatchIcon(rowIndex)" class="edit-icon" @click="setGlobal(record, 'warehouse')" />
            </div>
            <!-- 入库数 -->
            <div v-else-if="item.dataIndex == 'warehouseAmt'" class="cell flex-c" style="width: 80px">
              <a-input-number :precision="0" :min="0" v-model="record.warehouseAmt" style="width: 60px" placeholder="" hide-button />
              <icon-double-down v-if="showBatchIcon(rowIndex)" class="edit-icon" @click="setGlobal(record, 'warehouseAmt')" />
            </div>
            <!-- 主材重量 -->
            <div v-else-if="item.dataIndex == 'materialWeight'" class="cell flex-c" style="width: 80px">
              <a-input-number :precision="0" :min="0" v-model="record.materialWeight" style="width: 60px" placeholder="" hide-button />
              <icon-double-down v-if="showBatchIcon(rowIndex)" class="edit-icon" @click="setGlobal(record, 'materialWeight')" />
            </div>

            <!-- 材质金额 -->
            <span v-else-if="item.dataIndex == 'materialAmount'">￥{{ (Number(record.materialWeight || 0) * Number(record.materialPrice || 0)).toFixed(2) }}</span>
            <!-- 产品金额 -->
            <span v-else-if="item.dataIndex == 'productAmount'">￥{{ (Number(record.warehouseAmt || 0) * Number(record.productPrice || 0)).toFixed(2) }}</span>
            <!-- 工费 -->
            <span v-else-if="item.dataIndex == 'laborAmount'">￥{{ (Number(record.warehouseAmt || 0) * Number(record.laborPrice2 || 0)).toFixed(2) }}</span>
            <!-- 其他费用 -->
            <div v-else-if="item.dataIndex == 'otherAmount'" class="cell flex-c" style="width: 80px">
              <a-input-number :precision="2" :min="0" v-model="record.otherAmount" style="width: 60px" placeholder="" hide-button />
              <icon-double-down v-if="showBatchIcon(rowIndex)" class="edit-icon" @click="setGlobal(record, 'otherAmount')" />
            </div>
            <!-- 合计金额 -->
            <span v-else-if="item.dataIndex == 'totalAmount'">￥{{ getTotalAmount(record).toFixed(2) }}</span>
            <!-- 税率 -->
            <div v-else-if="item.dataIndex == 'rate'" class="cell flex-c" style="width: 160px">
              <a-select v-model="record.priceType" size="medium" style="width: 70px">
                <a-option :value="0">不含税</a-option>
                <a-option :value="1">含税</a-option>
              </a-select>
              <a-input-number v-model="record.rate" style="width: 60px" hide-button placeholder="" />
              <span>%</span>
              <icon-double-down v-if="showBatchIcon(rowIndex)" class="edit-icon" @click="setGlobal(record, 'rate')" />
            </div>
            <!-- 税金 -->
            <span v-else-if="item.dataIndex == 'rateAmount'">￥{{ ((getTotalAmount(record) * Number(record.rate || 0)) / 100).toFixed(2) }}</span>
            <!-- 单件货值 -->
            <span v-else-if="item.dataIndex == 'value'">￥{{ getTotalValue(record).toFixed(2) }}</span>

            <p v-else-if="['materialPrice', 'laborPrice2', 'productPrice'].includes(item.dataIndex)">￥{{ record[item.dataIndex] }}</p>
            <p v-else>{{ record[item.dataIndex] }}</p>
          </template>
        </a-table-column>
        <a-table-column title="操作" :width="60" fixed="right">
          <template #cell="{ rowIndex }">
            <a-popconfirm v-if="detailInfo.billItems.length > 1" content="确定是否移除?" @ok="detailInfo.billItems.splice(rowIndex, 1)" type="error">
              <a-button type="text">移除</a-button>
            </a-popconfirm>
          </template>
        </a-table-column>
      </template>
    </a-table>
  </a-modal>
</template>
<script lang="ts" setup>
  import { ref, onMounted } from 'vue'
  import { Message } from '@arco-design/web-vue'
  import { getReceiptInfo, updatePurchaseReceipt } from '@/api/purchaseApplication'
  import useBaseDataStore from '@/store/modules/base-data'
  import { parseJson } from '@/utils'

  onMounted(() => {
    getWareHouseList()
    getDetail()
  })
  const emit = defineEmits(['closed', 'success'])
  const props = defineProps({
    isShow: {
      type: Boolean,
      default: false,
    },
    currentId: {
      type: String,
    },
  })
  const tableColumns: Array<any> = [
    {
      title: '产品',
      dataIndex: 'sku',
      width: 160,
      fixed: 'left',
    },
    {
      title: '扣减库存',
      dataIndex: 'outWarehouse',
      tip: '如果需要扣减本地仓库的库存就需要选择一个仓库。这里的库存扣减并非实时反应的，系统每天凌晨1点统一扣减天一的库存。',
      width: 160,
    },
    {
      title: '申购数量',
      dataIndex: 'planAmt',
      width: 70,
    },
    {
      title: '材质单价(元/g)',
      dataIndex: 'materialPrice',
      tip: '材质单价，取采购参数材质对应的报价，该报价每天都有变化，取申购订单被接单日的材质报价',
      width: 80,
    },

    {
      title: '产品单价',
      dataIndex: 'productPrice',
      tip: '产品单价：单个产品的成本价，默认值从该申购单关联的采购单上获取',
      width: 60,
    },
    {
      title: '工费单价',
      dataIndex: 'laborPrice2',
      tip: '工费是指采购人员的服务费，是在申购单接单时确定好的，在此无法修改',
      width: 60,
    },
    {
      title: '入库数',
      dataIndex: 'warehouseAmt',
      tip: '入库数量：如果需要扣减库存的，入库数量必须小于等于现货库存数',
      width: 100,
    },
    {
      title: '入库材质重(g)',
      dataIndex: 'materialWeight',
      tip: '金银等贵金属首饰类产品是按材质重量计算价格的，所以入库时必须要有材质重量。默认值=关联的采购订单上的单件材质重量*入库数量',
      width: 100,
    },
    {
      title: '材质金额',
      dataIndex: 'materialAmount',
      tip: '材质金额=材质单价*入库材质重',
      width: 80,
    },
    {
      title: '产品金额',
      dataIndex: 'productAmount',
      tip: '产品费用=产品单价*入库数',
      width: 80,
    },
    {
      title: '工费',
      dataIndex: 'laborAmount',
      tip: '工费=工费单价*入库数',
      width: 80,
    },
    {
      title: '其他费用',
      dataIndex: 'otherAmount',
      tip: '其他费用：本次采购入库产生的其他费用',
      width: 100,
    },
    {
      title: '合计金额',
      dataIndex: 'totalAmount',
      tip: '合计金额=材质金额+产品金额+其他费用+工费',
      width: 80,
    },
    {
      title: '税率',
      dataIndex: 'rate',
      tip: '是否含税和税率，默认从绑定的采购单上获取',
      width: 180,
    },
    {
      title: '税金',
      dataIndex: 'rateAmount',
      tip: '税金=合计金额*税率',
      width: 80,
    },
    {
      title: '单件货值',
      dataIndex: 'value',
      tip: '含税单件货值=（合计金额-税金）/入库数量 --不含税单件货值=合计金额/入库数量',
      width: 80,
    },
  ]

  const showEditDialog = ref(props.isShow)
  const submitLoading = ref(false)
  const useBaseData = useBaseDataStore()
  const detailInfo = ref<any>({})
  // 获取仓库列表
  async function getWareHouseList() {
    await useBaseData.getWareHouseList()
  }
  // 获取详情
  async function getDetail() {
    if (!props.currentId) return
    const res: any = await getReceiptInfo({ id: props.currentId })
    detailInfo.value = res?.data || {}
    detailInfo.value.billItems.forEach((item: any) => {
      item.laborPrice2 = item.laborPriceType === 1 ? item.laborPrice : Number(item.productPrice || 0) * Number((item.laborRate || 0) / 100)
      let purchaseSpecs = item.purchaseSpecs ? parseJson(item.purchaseSpecs, {}) : {}
      item.purchaseSpecsArr = Object.values(purchaseSpecs)
      if (item.outWarehouseCode) {
        item.warehouse = {
          warehouseCode: item.outWarehouseCode,
          warehouseName: item.outWarehouseName,
        }
      }
    })
  }

  //设置全局
  async function setGlobal(item: any, key: string) {
    detailInfo.value.billItems.forEach((el: any) => {
      el[key] = item[key]
    })
  }

  // 是否显示批量编辑按钮
  function showBatchIcon(index: number) {
    return index < detailInfo.value.billItems.length
  }
  // 获取合计金额
  function getTotalAmount(row: any) {
    let materialAmount = Number(row.materialWeight || 0) * Number(row.materialPrice || 0)
    let productAmount = Number(row.warehouseAmt || 0) * Number(row.productPrice || 0)
    let laborAmount = Number(row.warehouseAmt || 0) * Number(row.laborPrice2 || 0)
    let otherAmount = Number(row.otherAmount || 0)
    return materialAmount + productAmount + laborAmount + otherAmount
  }
  // 获取单件货值
  function getTotalValue(row: any) {
    let totalAmount = getTotalAmount(row)
    let rateAmount = row.priceType === 0 ? 0 : (totalAmount * Number(row.rate || 0)) / 100
    return row.warehouseAmt ? (totalAmount - rateAmount) / row.warehouseAmt : 0
  }
  // 关闭
  function closedDialog() {
    showEditDialog.value = false
    emit('closed')
  }
  // 保存
  async function submitData() {
    let _parmas: any = {
      attachment: detailInfo.value.attachment,
      id: detailInfo.value.id,
      planId: detailInfo.value.planId,
      receivingAddress: detailInfo.value.receivingAddress,
      remark: detailInfo.value.remark,
    }

    _parmas.billItems = detailInfo.value.billItems.map((item: any) => {
      let billObj: any = {
        deductionType: item.warehouse?.warehouseCode ? 1 : 0,
        materialWeight: item.materialWeight,
        otherAmount: item.otherAmount,
        planId: item.planId,
        planItemId: item.planItemId,
        priceType: item.priceType,
        productPrice: item.productPrice,
        rate: item.rate,
        id: item.id,
        warehouseAmt: item.warehouseAmt,
        outWarehouseCode: item.warehouse?.warehouseCode,
        outWarehouseName: item.warehouse?.warehouseName,
      }
      return billObj
    })
    console.log(_parmas)
    let res: any = await updatePurchaseReceipt(_parmas)
    if (!res) return false
    Message.success('提交成功')
    emit('success')
    closedDialog()
  }
  // 显示sku规格
  function getProductSpecs(item: any) {
    let productSpecs = item.productSpecs ? parseJson(item.productSpecs, []) : []
    return productSpecs.map((el: any) => el.valueCn)?.join('*') || '--'
  }
</script>
<style lang="less" scoped>
  .detail-item {
    margin-bottom: 5px;
    .label {
      width: 120px;
      text-align: right;
    }
    .val {
      color: #666;
    }
    .info {
      font-size: 12px;
      color: #999;
    }
  }
  .header {
    font-size: 14px;
    font-weight: bold;
    margin-bottom: 20px;
    border-left: 3px solid rgba(var(--primary-6), 0.5);
    padding-left: 10px;
    .title {
      margin-right: 30px;
      width: 90px;
    }
  }
  .edit-icon {
    font-size: 16px;
    margin-left: 5px;
    cursor: pointer;
  }
  :deep(.arco-table-td) {
    .arco-table-cell {
      padding: 2px 5px;
    }
    .arco-select-view-single {
      padding: 0 5px;
    }
    .arco-input-wrapper {
      padding: 0 5px;
    }
    .arco-select-view-value {
      font-size: 12px !important;
      min-height: 26px;
    }
    .arco-input {
      font-size: 12px !important;
    }
  }
</style>
